package com.miao.hong.fang.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Hex;

public class SecurityUtil {
	
	private static SecretKey decryptKey = null;
	private static final String keyPath = "D:\\key";

	public static String encryptPwd(String password) throws Exception {
		
		MessageDigest md = MessageDigest.getInstance("SHA-256");
		md.update(password.getBytes("utf-8"));
		byte[] resultByte = md.digest();
		String result = new String(Hex.encodeHex(resultByte));
		return result;
	}
	
	public static byte[] encryptImage(byte[] input) throws Exception {

		File keyFile = new File(keyPath);
		if(!keyFile.exists()) {
			//generate the key
			KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
			SecureRandom sr = new SecureRandom();
			keyGenerator.init(128, sr);
			SecretKey key = keyGenerator.generateKey();

			//store the key
			OutputStream os = null;
			InputStream is = null;

			os = new FileOutputStream(keyFile);
			is = new ByteArrayInputStream(key.getEncoded());		
			byte[] b = new byte[1024];
			int count = is.read(b);
			while(count > -1) {
				os.write(b, 0, count);
				count = is.read(b);
			}
			is.close();
			os.close();
			
			decryptKey = key;
		} else {
			//read the key
			decryptKey = readKey();
		}

		
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, decryptKey);
		byte[] result = cipher.doFinal(input);
		
		return result;
	}
	
	public static byte[] decryptImage(byte[] input) throws Exception {
		
		if(decryptKey == null) {
			//read the key
			decryptKey = readKey();
			System.out.println("I have read the key");
		}
		
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, decryptKey);
		byte[] result = cipher.doFinal(input);
		
		return result;
	}
	
	public static SecretKey readKey() throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		FileInputStream fis = new FileInputStream(keyPath);
		
		byte[] b = new byte[1024];
		int count = fis.read(b);
		while(count > -1) {
			bos.write(b, 0, count);
			count = fis.read(b);
		}
		bos.close();
		fis.close();
		
		SecretKey secretKey = new SecretKeySpec(bos.toByteArray(), "AES");
		
		return secretKey;
	}
}









